import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';

export function exportExcleUtils(tHeader: any, filterVal: any, listData: any, fileName: any) {
	//设置工作簿属性
	const workbook = new ExcelJS.Workbook();
	workbook.creator = 'Me';
	workbook.lastModifiedBy = 'Her';
	workbook.created = new Date();
	workbook.modified = new Date();
	workbook.lastPrinted = new Date();
	//添加工作薄
	const worksheet = workbook.addWorksheet('sheet1');
	//计算标题宽
	let colWidth = calculateColumnWidth(tHeader);
	console.log(colWidth);
	let style = { alignment: { vertical: 'middle', horizontal: 'center' } };
	let columns = [];
	for (let i = 0; i < tHeader.length; i++) {
		let header = {
			header: tHeader[i],
			key: filterVal[i] ? filterVal[i] : i + '',
			width: colWidth[i] ? colWidth[i] + 10 : 10,
			style: JSON.parse(JSON.stringify(style)),
		};
		columns.push(header);
	}
	worksheet.columns = columns;

	//添加数据
	listData.forEach((item: any) => {
		worksheet.addRow(item);
	});

	worksheet.getRow(1).font = { name: '宋体', family: 4, size: 16, bold: true };

	fileName = fileName + '.xlsx';
	workbook.xlsx.writeBuffer().then((data: any) => {
		let blob = new Blob([data], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		});
		saveAs(blob, fileName);
	});
}

export function calculateColumnWidth(tHeader: any) {
	let colWidth = [];
	//计算列宽
	for (let i = 0; i < tHeader.length; i++) {
		if (colWidth[i] && colWidth[i] < tHeader[i].length) {
			colWidth[i] = tHeader[i].length;
		} else if (colWidth[i] == undefined) {
			colWidth[i] = tHeader[i].length;
		}
	}
	console.log(colWidth);
	return colWidth;
}
